﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using PInitiatives.Models;

namespace PInitiatives.Outlook
{
    public class OutlookMeetingSender
    {

        internal static void SendICalendarEmail(string invitationString, string senderAddress, string senderPassword, string recieverAddress, int initiativeID)
        {
            //create calendar meeting request
            String meetingInfo = invitationString;
            System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/calendar; method=REQUEST");
            AlternateView ICSview = AlternateView.CreateAlternateViewFromString(meetingInfo, mimeType);

            var fromAddress = new MailAddress(senderAddress, "From " + senderAddress);
            var toAddress = new MailAddress(recieverAddress, "To " + recieverAddress);
            string fromPassword = senderPassword;

            //create email message with alternative view containing callendar request
            MailMessage message = new MailMessage(fromAddress, toAddress);
            message.AlternateViews.Add(ICSview);

            //connect to gmail smtp sever
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            //send the message
            try
            {
                smtp.Send(message);
                PInitiativesEntities db = new PInitiativesEntities();
                InitiativeUser initativeUser = new InitiativeUser();
                initativeUser.InitiativeID = initiativeID;
                //Label1.Text = "Wiasomosc wyslana pomyslnie! do: " + recieverAddress;
            }
            catch (Exception ex)
            {
                //Label1.Text = ex.ToString();
            }
        }
    }
}